package com.idealighter.game.games.happyfive.util;

import com.google.common.collect.Lists;

import com.idealighter.game.games.happyfive.struct.cards.Card;
import com.idealighter.game.games.happyfive.struct.cards.CardNumber;
import com.idealighter.game.games.happyfive.struct.cards.CardSuit;
import com.idealighter.game.games.happyfive.struct.cards.CardType;

import java.util.List;
import java.util.stream.Collectors;

/**
 * hing . 牌值计算器 .
 * 
 * @date 2015年10月28日 下午18:47:20
 * @date
 */
public class HandPower implements Comparable<com.idealighter.game.games.happyfive.util.HandPower> {
  private final CardType handPowerType;
  private final List<CardNumber> tieBreakingInformation;
  private final List<Card> cardList;

  /**
   * 构造函数 .
   * 
   * @param handPowerType .
   * @param tieBreakingInformation .
   * @param cardList .
   */
  public HandPower(final CardType handPowerType, final List<CardNumber> tieBreakingInformation,
      final List<Card> cardList) {
    this.handPowerType = handPowerType;
    this.tieBreakingInformation = tieBreakingInformation;
    this.cardList = cardList;
  }

  @Override
  public int compareTo(com.idealighter.game.games.happyfive.util.HandPower other) {
    int typeDifference = handPowerType.getPower() - other.handPowerType.getPower();
    if (typeDifference == 0) {
      if (tieBreakingInformation.size() != other.tieBreakingInformation.size()) {
        System.err.println("长度不一致");
      }
      for (int i = 0; i < tieBreakingInformation.size(); i++) {
        int tieDifference = tieBreakingInformation.get(i).getPower()
            - other.tieBreakingInformation.get(i).getPower();
        if (tieDifference != 0) {
          return tieDifference;
        }
      }
      return compareSuit(tieBreakingInformation.get(tieBreakingInformation.size() - 1), cardList)
          - compareSuit(other.tieBreakingInformation.get(other.tieBreakingInformation.size() - 1),
              other.cardList);
    }

    return typeDifference;
  }


  /**
   * .
   * 
   * @param cardNumber .
   * @param cardLists .
   * @return
   */
  public int compareSuit(CardNumber cardNumber, List<Card> cardLists) {
    List<CardSuit> suit = Lists.newArrayList();
    suit.addAll(cardLists.stream().filter(card -> card.getNumber() == cardNumber).map(Card::getSuit)
        .collect(Collectors.toList()));
    return getMaxSuit(suit);
  }


  /**
   * .
   * 
   * @param cardSuitList .
   * @return
   */
  public int getMaxSuit(List<CardSuit> cardSuitList) {
    int suitPower = 0;
    for (CardSuit suit : cardSuitList) {
      if (suit.getPower() >= suitPower) {
        suitPower = suit.getPower();
      }
    }
    return suitPower;
  }


  @Override
  public String toString() {
    return handPowerType.toString() + " " + tieBreakingInformation.toString();
  }

  public CardType getHandPowerType() {
    return handPowerType;
  }

  public List<CardNumber> getTieBreakingInformation() {
    return tieBreakingInformation;
  }
}
